﻿using System;
using System.Drawing;
using Space.Library.Extensions;
using Space.Model.Entity;

namespace Space.Model.Fsm
{
    /// <summary>
    /// Sets orientation to most accurate direction.
    /// Moves the ship in a straight line to the target. 
    /// </summary>
    public class RotateToTargetState : IState<Ship>
    {
        public bool AcceptInput { get { return false; } }

        public Ship Owner { get; set; }
        private readonly Point _targetCoords;

        private float _rotateIncrement;
        private float _targetAngle;

        public RotateToTargetState(Point targetCoords)
        {
            _targetCoords = targetCoords;
        }

        public void Enter()
        {
            _targetAngle = Owner.BoardCoords.AsVectorToMid().FindAngleToTarget(_targetCoords.AsVectorToMid());

            if (float.IsNaN(_targetAngle)) // Clicked on self.
                Owner.Fsm.RevertToPreviousState();

            float angleDiff = _targetAngle - Owner.Orientation;
            _rotateIncrement = (angleDiff > 180 || angleDiff < 0) ? -1 : +1;
        }

        public void Execute(long timestep)
        {
            float stepRotation = _rotateIncrement * timestep * 0.1f;

            float diff = _targetAngle - Owner.Orientation;
            if (Math.Abs(diff) < Math.Abs(stepRotation)) // more to do
            {
                Owner.Rotate(diff);
                Owner.Fsm.ChangeState(new MoveToTargetState(_targetCoords));
                return;
            }

            Owner.Rotate(stepRotation);
        }

        public void Exit()
        {
            // Clear steering
        }
    }
}
